package com.lc.rocketmq.service;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisCallback;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;

import java.util.concurrent.TimeUnit;

/**
 * @author liuc
 * @date 2021/8/21
 * @description
 **/
@Component
public class RedisService {
    @Autowired
    private RedisTemplate<String,Object> redisTemplate;

    public void set(String key, String value, int timeout){
        if(timeout > 0){
            redisTemplate.opsForValue().set(key,value,timeout,TimeUnit.SECONDS);
        }else{
            redisTemplate.opsForValue().set(key,value);
        }
    }

    public long incr(String key, long val){
        return redisTemplate.opsForValue().increment(key,val);
    }

    public String get(String key){
        return (String) redisTemplate.opsForValue().get(key);
    }

    public boolean lock(String key){
        return redisTemplate.opsForValue().setIfAbsent(key,"1",3, TimeUnit.SECONDS);
    }
}
